package com.hmy.uaa.common.security;

import com.hmy.uaa.dto.UserDTO;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 根据上下文获取用户认证信息
 */
public class UserOAuth2Details {

    private static final String ID = "id";
    private static final String NAME = "name";

    private static Optional<Map<String, Object>> getUser() {
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        return Optional.ofNullable(details)
                .map(authentication -> {
                    // 各个微服务会取到Map
                    if (authentication instanceof Map) {
                        return (Map<String, Object>) authentication;
                    }

                    return null;
                });

    }

    public static UserDTO getUserDTO() {
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        Map<String, Object> decodedDetails = (Map) details.getDecodedDetails();
        String phone = decodedDetails.get(UserDTO.PHONE).toString();
        String id = decodedDetails.get(UserDTO.ID).toString();
        List<String> roleList = (List<String>) decodedDetails.get(UserDTO.ROLES);
        Long departmentId = Long.valueOf(decodedDetails.get(UserDTO.DEPARTMENT_ID).toString());
        Long companyId = Long.valueOf(decodedDetails.get(UserDTO.COMPANY_ID).toString());
        return UserDTO.builder().phone(phone).id(id).roles(roleList).companyId(companyId).departmentId(departmentId).build();
    }

    public static String getUsername() {


        return getUser()
                .map(user -> user.get(NAME))
                .map(Object::toString)
                .orElse(null);

    }
}
